<template>
  <el-card style="width: 100%">
    <!-- 主体内容区 -->
    <div class="content-wrapper">
      <!-- 左侧分类树 -->
      <div class="category-menu">
        <el-tree
          :data="categoryTree"
          :props="defaultProps"
          @node-click="handleNodeClick"
          default-expand-all
          highlight-current
        />
      </div>
      <!-- 右侧商品表格 -->
      <div class="products-list">
        <!-- 添加统计数据展示 -->
        <div class="statistics-bar">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">全部商品</div>
                <div class="stat-value">{{ total }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">销售中</div>
                <div class="stat-value selling">
                  {{
                    tableData.filter(
                      (item) => item.status === 1 && item.spuStockQuantity > 0
                    ).length
                  }}
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">已售罄</div>
                <div class="stat-value soldout">
                  {{
                    tableData.filter((item) => item.spuStockQuantity === 0)
                      .length
                  }}
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">已下架</div>
                <div class="stat-value offline">
                  {{ tableData.filter((item) => item.status === 0).length }}
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 添加 tab 和操作按钮区域 -->
        <div class="table-header">
          <el-tabs
            v-model="activeTab"
            class="flex-grow"
            @tab-change="handleTabChange"
          >
            <el-tab-pane label="全部" name="all" />
            <el-tab-pane label="销售中" name="selling" />
            <el-tab-pane label="已售罄" name="soldout" />
            <el-tab-pane label="已下架" name="offline" />
          </el-tabs>
          <el-button type="primary" @click="handleCreate">新建商品</el-button>
        </div>

        <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="item in options"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
            :width="item.width"
            :formatter="
              item.prop !== 'primaryImage' ? item.formatter : undefined
            "
          >
            <template #default="scope" v-if="item.prop === 'primaryImage'">
              <div class="image-container">
                <el-image
                  :src="scope.row.primaryImage"
                  :alt="scope.row.title"
                  fit="cover"
                  :style="{ width: '100px', height: '100px' }"
                />
                <div
                  v-if="
                    scope.row.status === 0 || scope.row.spuStockQuantity === 0
                  "
                  class="status-label"
                >
                  {{ scope.row.spuStockQuantity === 0 ? "已售罄" : "已下架" }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button-group>
                <el-button size="small" @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button
                  size="small"
                  type="primary"
                  @click="handleTopProduct(row)"
                >
                  <el-icon><Top /></el-icon>
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->

        <div class="pagination-container">
          <el-pagination
            v-model:currentPage="querForm.page"
            v-model:page-size="querForm.pagesize"
            :page-sizes="[2, 5, 10]"
            :small="false"
            :disabled="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import {
  Delete,
  Edit,
  Search,
  Share,
  Setting,
  Upload,
  Top,
} from "@element-plus/icons-vue";
import { getCategories } from "@/api/category";
import { formatTreeData } from "@/utils/public";
import { useRouter } from "vue-router";
import { options } from "./options.js";
import { usePageCurrentCategoryStore } from "@/stores/pageStore";
import { getGoods, deleteGood } from "@/api/good";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();

// 添加 activeTab 的定义
const activeTab = ref("all"); // 默认选中"全部"标签页

// 查询参数
const querForm = ref({
  search: "",
  sortBy: "adminName",
  ascending: true,
  page: 1,
  pageSize: 5,
  status: "all",
});

const total = ref(0);
const categoryTree = ref([]);
const currentCategory = usePageCurrentCategoryStore();
const tableData = ref([]);

// 获取分类列表
const initGetCategory = async () => {
  try {
    const res = await getCategories();

    // 添加空值检查
    if (res.data && res.data.data) {
      // 将扁平数据转换为树形结构
      categoryTree.value = formatTreeData(res.data.data, "id", "parentId");
    } else {
      categoryTree.value = [];
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失败");
    categoryTree.value = [];
  }
};

// 分类树默认配置
const defaultProps = {
  children: "children",
  label: "name",
};

// 添加状态过滤函数
const filterTableData = (data) => {
  if (!data) return [];

  switch (activeTab.value) {
    case "selling":
      return data.filter(
        (item) => item.status === 1 && item.spuStockQuantity > 0
      );
    case "soldout":
      return data.filter((item) => item.spuStockQuantity === 0);
    case "offline":
      return data.filter((item) => item.status === 0);
    default:
      return data;
  }
};

// 修改加载商品列表方法
const loadGoodsList = async () => {
  try {
    const params = {
      pageSize: querForm.value.pageSize,
      pageIndex: querForm.value.page,
      categoryId: currentCategory.currentCategory,
      keyword: querForm.value.search || "",
    };

    // 根据 activeTab 添加状态查询
    switch (activeTab.value) {
      case "selling":
        params.status = 1;
        break;
      case "soldout":
        params.stockStatus = 0;
        break;
      case "offline":
        params.status = 0;
        break;
      // 'all' 不需要添加额外参数
    }

    const res = await getGoods(params);

    if (res.data) {
      // 过滤并处理数据
      const filteredData = filterTableData(res.data.data);
      tableData.value = filteredData.map((item) => ({
        ...item,
        salePrice: item.salePrice || 0,
        linePrice: item.linePrice || 0,
        statusText: getStatusText(item.status, item.spuStockQuantity),
        statusType: getStatusType(item.status, item.spuStockQuantity),
      }));

      // 更新总数
      total.value = res.data.total;
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败");
  }
};

// 修改 tab 切换处理函数
const handleTabChange = (tab) => {
  activeTab.value = tab;
  querForm.value.page = 1; // 重置页码
  loadGoodsList(); // 重新加载数据
};

// 添加状态文本获取函数
const getStatusText = (status, stockQuantity) => {
  if (status === 0) return "已下架";
  if (stockQuantity === 0) return "已售罄";
  return "销售中";
};

// 添加状态类型获取函数（用于样式）
const getStatusType = (status, stockQuantity) => {
  if (status === 0) return "danger";
  if (stockQuantity === 0) return "warning";
  return "success";
};

// 修改表格列配置，添加状态列
const tableColumns = [
  // ... 其他列保持不变 ...
  {
    label: "状态",
    prop: "statusText",
    width: 100,
    formatter: (row) => {
      return h(
        ElTag,
        {
          type: row.statusType,
          effect: "light",
        },
        () => row.statusText
      );
    },
  },
];

// 处理函数
const handleNodeClick = (data) => {
  currentCategory.currentCategory = data.id;
  loadGoodsList();
};

const handleSizeChange = (val) => {
  querForm.value.pageSize = val;
  loadGoodsList();
};

const handleCurrentChange = (val) => {
  querForm.value.page = val;
  loadGoodsList();
};

// 添加新建商品处理函数
const handleCreate = () => {
  router.push({
    path: "/goods/update",
    query: {},
  });
};

// 在 onMounted 中添加加载商品列表
onMounted(() => {
  initGetCategory();
  loadGoodsList();
});

// 修改删除处理函数
const handleDelete = (row) => {
  console.log("商品数据:", row);

  ElMessageBox.confirm("确认删除该商品吗？删除后不可恢复", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const spuId = row.spuId;
        if (!spuId) {
          throw new Error("商品ID不存在");
        }

        await deleteGood(spuId);
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        // 如果当前页只有一条数据，且不是第一页，则跳转到上一页
        if (tableData.value.length === 1 && querForm.value.page > 1) {
          querForm.value.page--;
        }
        // 重新加载列表数据
        loadGoodsList();
      } catch (error) {
        ElMessage({
          type: "error",
          message: error.message || "删除失败",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 添加置顶处理函数
const handleTopProduct = (row) => {
  ElMessage({
    type: "success",
    message: "置顶成功",
  });
};

// 修改 handleEdit 函数
const handleEdit = (row) => {
  router.push({
    path: "/goods/update",
    query: { id: row.spuId }, // 传递商品ID作为参数
  });
};
</script>

<style scoped>
.content-wrapper {
  display: flex;
  gap: 20px;
  background-color: #fff;
  border-radius: 4px;
  height: calc(100vh - 160px);
  overflow: hidden;
}

.category-menu {
  width: 220px;
  border-right: 1px solid #ebeef5;
  padding: 10px;
  overflow-y: auto;
}

.products-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  padding-right: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}

.price {
  color: #f56c6c;
  font-weight: 500;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409eff;
}

/* 添加新的样式 */
.table-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.flex-grow {
  flex-grow: 1;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

.header-button {
  margin-left: 16px;
}

/* 调整tab样式，去除底部边框 */
:deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.product-list {
  padding: 20px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-info.inactive {
  opacity: 0.6;
}

.image-container {
  position: relative;
  width: 100px;
}

.status-label {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  text-align: center;
  padding: 2px 0;
  font-size: 12px;
}

.product-name {
  font-weight: bold;
}

:deep(.el-card) {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  flex: 1;
  padding: 20px;
  overflow: hidden;
}

:deep(.el-button-group) {
  display: flex;
  gap: 0; /* 移除按钮之间的间距 */
}

:deep(.el-button-group .el-button) {
  padding: 4px 8px; /* 减小按钮的内边距 */
}

/* 添加统计卡片样式 */
.statistics-bar {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  text-align: center;
}

.stat-title {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-value.selling {
  color: #67c23a;
}

.stat-value.soldout {
  color: #e6a23c;
}

.stat-value.offline {
  color: #f56c6c;
}

/* 表格状态标签样式 */
:deep(.el-tag) {
  margin: 0 2px;
}
</style>
